package com.mk.httpCon;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpDemo {

	// localhost:8081/allowence/postMsg : ××××××
	private final static String url = "http://localhost:8081/allowence/postMsg"; //√√
	
	@Test
	public void test1() throws Exception, IOException {
		JSONObject json = new JSONObject();
		json.put("code", "我是你爷爷！！");
		//绑定到请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
		StringEntity se = new StringEntity(json.toString(), "UTF-8");
		se.setContentType("text/json");
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		httpPost.setEntity(se);

		//发送请求
		HttpClient client = HttpClientBuilder.create().build();
		HttpResponse response = client.execute(httpPost);
		
		HttpEntity httpEntity = response.getEntity();
		System.out.println("--------------返回结果------------");
//		System.out.println(httpEntity); //ResponseEntityProxy{[Content-Type: text/plain;charset=UTF-8,Content-Length: 45,Chunked: false]}
		String result = EntityUtils.toString(httpEntity);
		System.out.println(result); //端口: 8081,{"code":"我是你爷爷！！"}
	}
}
